package middleware

import (
	"gin_web/config"
	"gin_web/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenStr := ctx.Request.Header.Get("Authorization")
		if tokenStr == "" {
			utils.TokenFail(ctx)
			ctx.Abort()
			return
		}

		tokenStr = tokenStr[len(utils.TokenType)+1:]
		jwtClaims, err := utils.ParseJwt(tokenStr)
		if err != nil {
			utils.CustomErrR(ctx, http.StatusUnauthorized, err)
			ctx.Abort()
			return
		}
		expirationTime, err := jwtClaims.GetExpirationTime()
		if err != nil || expirationTime.Before(time.Now()) {
			utils.TokenFail(ctx)
			ctx.Abort()
			return
		}
		issuer, _ := jwtClaims.GetIssuer()
		if issuer != config.GConfig.Jwt.Issuer {
			utils.TokenFail(ctx)
			ctx.Abort()
			return
		}
		ctx.Set("token", tokenStr)
		ctx.Set("id", jwtClaims.ID)
	}
}
